package com.eeepay.eeepay_v2.activity;

import android.graphics.Color;
import android.text.TextUtils;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.ColorUitls;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.util.MathUtils;
import com.eeepay.eeepay_v2.util.TimeUtils;
import com.eeepay.eeepay_v2.view.LegendView;
import com.eeepay.v2_library.log.LogUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.view.TitleBar;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.AgentApiServiceGrpc;
import cn.eeepay.api.grpc.nano.AgentSerProto;
import cn.eeepay.api.grpc.nano.TransApiServiceGrpc;
import cn.eeepay.api.grpc.nano.TransProto;
import io.grpc.ManagedChannel;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.view.PieChartView;

import static com.eeepay.eeepay_v2.util.ColorUitls.colors;

/**
 * Created by zw on 2016/3/8 0008.
 * 我的商户、 今日新增商户、 分润明细、  等  饼状图界面
 */
public class MyMerchantActivity extends ABBaseActivity {
    private String intentFlag;
    private TitleBar titleBar;
    private TextView tv_title;
    //----------------add by zhuangzeqin 2017年8月29日12:02:02 更换新的饼图插件；解决第一次进来显示不了饼图的bug----------------------------
    private PieChartView pieChartView;//饼图2
    private PieChartData pieChardata;//add by zhuangzeqin 2017年8月29日12:02:02 更换新的饼图插件；解决第一次进来显示不了饼图的bug
    private List<SliceValue> values = new ArrayList<SliceValue>();//饼图数据的封装
    //----------------add by end --------------------------------
    private LinearLayout lLayout_legend;
    private LegendView[] legends;//说明文字
    private String date;//日期
    private AgentSerProto.ProductMsg[] productMsg;
    private TransProto.ProfitInfo[] profitInfo;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_merchant;
    }

    @Override
    protected void initWidget() {
        titleBar = getViewById(R.id.title_bar);
        tv_title = getViewById(R.id.tv_content_title);
        intentFlag = bundle.getString(Constant.INTENT_FLAG);
        if (TextUtils.isEmpty(intentFlag)) {
            return;
        }
        if (Constant.MY_MERCHANT.equals(intentFlag)) {//我的商户
            titleBar.setTiteTextView("我的商户");
            tv_title.setText("所有商户数量");
        } else if (Constant.TODAY_MERCHANT.equals(intentFlag)) {//今日新增商户
            titleBar.setTiteTextView("今日新增商户");
            tv_title.setText("今日新增商户数量");
        } else if (Constant.WEEK_PROFIT.equals(intentFlag)) { //七日分润
            date = bundle.getString("date");
            tv_title.setText(date + "产品分润明细");
            titleBar.setTiteTextView("分润明细");
        }
        pieChartView = getViewById(R.id.pie_chart);
        lLayout_legend = getViewById(R.id.layout_legend);
        sendHttpRequest(0);
    }

    /**
     * 初始化饼状图
     */
    private void initPieChart() {
        pieChardata = new PieChartData();
        pieChardata.setHasLabels(false);//显示表情
        pieChardata.setHasLabelsOnlyForSelected(false);//不用点击显示占的百分比
        pieChardata.setHasLabelsOutside(false);//占的百分比是否显示在饼图外面
        pieChardata.setHasCenterCircle(true);//是否是环形显示
        pieChardata.setCenterCircleColor(Color.WHITE);//设置环形中间的颜色
        pieChardata.setCenterCircleScale(0.5f);//设置环形的大小级别
//        pieChardata.setCenterText1("饼图测试");//环形中间的文字1
//        pieChardata.setCenterText1Color(Color.BLACK);//文字颜色
//        pieChardata.setCenterText1FontSize(14);//文字大小

//        pieChardata.setCenterText2("饼图测试");
//        pieChardata.setCenterText2Color(Color.BLACK);.
//        pieChardata.setCenterText2FontSize(18);
        /**这里也可以自定义你的字体   Roboto-Italic.ttf这个就是你的字体库*/
//      Typeface tf = Typeface.createFromAsset(this.getAssets(), "Roboto-Italic.ttf");
//      data.setCenterText1Typeface(tf);
        pieChartView.setValueSelectionEnabled(false);//选择饼图某一块变大
        pieChartView.setAlpha(0.9f);//设置透明度
        pieChartView.setCircleFillRatio(1f);//设置饼图大小
    }

    /**
     * 设置饼状图的数据
     */
    private void setPieData() {
        initPieChart();
        //说明文字
        if (Constant.MY_MERCHANT.equals(intentFlag)
                || Constant.TODAY_MERCHANT.equals(intentFlag)) {//我的商户
            legends = new LegendView[productMsg.length];
            for (int i = 0; i < productMsg.length; i++) {
                legends[i] = new LegendView(mContext);
                legends[i].setName(productMsg[i].productName);
                legends[i].setCount(productMsg[i].merTotal + "个");
                lLayout_legend.addView(legends[i]);
            }
        } else if (Constant.WEEK_PROFIT.equals(intentFlag)) { //七日分润
            legends = new LegendView[profitInfo.length];
            for (int i = 0; i < profitInfo.length; i++) {
                legends[i] = new LegendView(mContext);
                legends[i].setName(profitInfo[i].bpName);
                legends[i].setCount(profitInfo[i].proProfitTotal + "元");
                lLayout_legend.addView(legends[i]);
            }
        }

        //获取饼状图数据
        getPieData();
    }

    @Override
    protected void eventOnClick() {

    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT, taskId, new GrpcUtils.AsyncTaskListener() {
            @Override
            public Object doInBack(ManagedChannel channel, int taskId) {
                if (Constant.MY_MERCHANT.equals(intentFlag)
                        || Constant.TODAY_MERCHANT.equals(intentFlag)) {//我的商户
                    AgentApiServiceGrpc.AgentApiServiceBlockingStub stub = AgentApiServiceGrpc
                            .newBlockingStub(channel)
                            .withDeadlineAfter(5, TimeUnit.SECONDS);
                    AgentSerProto.ReqDate request = new AgentSerProto.ReqDate();
                    //我的商户不传此参数,今日新增商户传这参数为当天时间有值就行
                    if (Constant.TODAY_MERCHANT.equals(intentFlag)) {
                        request.date = TimeUtils.getNowDate();
                    }
                    request.agentNode = UserInfo.getUserInfo2SP().getAgentNode();
                    AgentSerProto.AgentMerchantRes response = stub.queryAgentMerchant(request);
                    return response;
                } else if (Constant.WEEK_PROFIT.equals(intentFlag)) { //七日分润
                    TransApiServiceGrpc.TransApiServiceBlockingStub stub = TransApiServiceGrpc
                            .newBlockingStub(channel)
                            .withDeadlineAfter(5, TimeUnit.SECONDS);
                    TransProto.ReqTrans request = new TransProto.ReqTrans();
                    request.agentNo = UserInfo.getUserInfo2SP().getAgentNo();
                    request.transDate = date;
                    TransProto.EveryDayProfitRes response = stub.getEveryDayProfit(request);
                    return response;
                }
                return null;
            }

            @Override
            public void updateUI(Object result, int taskId) {
                dismissProgressDialog();
                if (result == null) {
                    showToast("查询失败");
                    return;
                }
                if (Constant.MY_MERCHANT.equals(intentFlag)
                        || Constant.TODAY_MERCHANT.equals(intentFlag)) {//我的商户
                    AgentSerProto.AgentMerchantRes response = (AgentSerProto.AgentMerchantRes) result;
                    if (!response.resStatus.status) {
                        showToast(response.resStatus.msg);
                        return;
                    }
                    productMsg = response.productMsg;
                    setPieData();
                } else if (Constant.WEEK_PROFIT.equals(intentFlag)) { //七日分润
                    TransProto.EveryDayProfitRes response = (TransProto.EveryDayProfitRes) result;
                    if (!response.resMsg.status) {
                        showToast(response.resMsg.msg);
                        return;
                    }
                    LogUtils.d("查询七日分润明细成功！ msg = " + response.resMsg.msg);
                    profitInfo = response.profitInfo;
                    setPieData();
                }
            }
        });
    }

    /**
     * 获取饼图数据
     */
    private void getPieData() {
        /**
         * 将一个饼形图分成 N 部分
         */
        float[] quarterly;
        if (Constant.MY_MERCHANT.equals(intentFlag)
                || Constant.TODAY_MERCHANT.equals(intentFlag)) {//我的商户
            quarterly = new float[productMsg.length];
            for (int i = 0; i < productMsg.length; i++) {
                quarterly[i] = MathUtils.String2Float(productMsg[i].merTotal);
                int parseColor;
                //封装饼图显示数据
//                SliceValue sliceValue = new SliceValue(quarterly[i], Color.parseColor(colors[i]));
                if (i > colors.length-1) {
                    //add by zhuangzeqin 2017年8月29日14:28:08 如果业务产品超过定义的颜色数组的长度；就生成随机颜色-- 避免由于数组的长度变化；导致数组越界
                    parseColor = Color.parseColor(ColorUitls.getColorByRandom());
                } else {
                    parseColor = Color.parseColor(colors[i]);//否则直接用定义的颜色数组的颜色值
                }
                SliceValue sliceValue = new SliceValue(quarterly[i], parseColor);
                values.add(sliceValue);//添加饼图数据
//                legends[i].setImageColor(Color.parseColor(colors[i]));//说明文字
                legends[i].setImageColor(parseColor);//说明文字
            }
        } else if (Constant.WEEK_PROFIT.equals(intentFlag)) { //七日分润
            quarterly = new float[profitInfo.length];
            for (int i = 0; i < profitInfo.length; i++) {
                quarterly[i] = MathUtils.String2Float(profitInfo[i].proProfitTotal);
                //封装饼图显示数据
//                SliceValue sliceValue = new SliceValue(quarterly[i], Color.parseColor(colors[i]));
                int parseColor;
                if (i > colors.length-1) {
                    //add by zhuangzeqin 2017年8月29日14:28:08 如果业务产品超过定义的颜色数组的长度；就生成随机颜色-- 避免由于数组的长度变化；导致数组越界
                    parseColor = Color.parseColor(ColorUitls.getColorByRandom());
                } else {
                    parseColor = Color.parseColor(colors[i]);//否则直接用定义的颜色数组的颜色值
                }
                SliceValue sliceValue = new SliceValue(quarterly[i], parseColor);
                values.add(sliceValue);//添加饼图数据
//                legends[i].setImageColor(Color.parseColor(colors[i]));//说明文字
                legends[i].setImageColor(parseColor);//说明文字
            }
        }
        pieChardata.setValues(values);//填充数据
        pieChartView.setPieChartData(pieChardata);
    }

}
